//
//  UIView_Extension.m
//  Simple_Imitated_QQ
//
//  Created by Zoo on 15-6-30.
//  Copyright (c) 2015年 Free. All rights reserved.
//

#import "UIView+Category.h"

@implementation UIView (Category)

@dynamic x;
@dynamic y;
@dynamic width;
@dynamic height;
@dynamic origin;
@dynamic size;

#pragma mark ---------------- Setters-----------------
-(void)setX:(CGFloat)x{
    CGRect r        = self.frame;
    r.origin.x      = x;
    self.frame      = r;
}

-(void)setY:(CGFloat)y{
    CGRect r        = self.frame;
    r.origin.y      = y;
    self.frame      = r;
}

-(void)setWidth:(CGFloat)width{
    CGRect r        = self.frame;
    r.size.width    = width;
    self.frame      = r;
}

-(void)setHeight:(CGFloat)height{
    CGRect r        = self.frame;
    r.size.height   = height;
    self.frame      = r;
}

-(void)setOrigin:(CGPoint)origin{
    self.x          = origin.x;
    self.y          = origin.y;
}

-(void)setSize:(CGSize)size{
    self.width      = size.width;
    self.height     = size.height;
}

-(void)setRight:(CGFloat)right {
    CGRect frame = self.frame;
    frame.origin.x = right - frame.size.width;
    self.frame = frame;
}

-(void)setBottom:(CGFloat)bottom {
    CGRect frame = self.frame;
    frame.origin.y = bottom - frame.size.height;
    self.frame = frame;
}

-(void)setCenterX:(CGFloat)centerX {
    self.center = CGPointMake(centerX, self.center.y);
}

-(void)setCenterY:(CGFloat)centerY {
    self.center = CGPointMake(self.center.x, centerY);
}

#pragma mark ---------------- Getters-----------------
-(CGFloat)x{
    return self.frame.origin.x;
}

-(CGFloat)y{
    return self.frame.origin.y;
}

-(CGFloat)width{
    return self.frame.size.width;
}

-(CGFloat)height{
    return self.frame.size.height;
}

-(CGPoint)origin{
    return CGPointMake(self.x, self.y);
}

-(CGSize)size{
    return CGSizeMake(self.width, self.height);
}

-(CGFloat)right {
    return self.frame.origin.x + self.frame.size.width;
}

-(CGFloat)bottom {
    return self.frame.origin.y + self.frame.size.height;
}

-(CGFloat)centerX {
    return self.center.x;
}

-(CGFloat)centerY {
    return self.center.y;
}

-(UIView *)lastSubviewOnX{
    if(self.subviews.count > 0){
        UIView *outView = self.subviews[0];
        
        for(UIView *v in self.subviews)
            if(v.x > outView.x)
                outView = v;
        
        return outView;
    }
    
    return nil;
}

-(UIView *)lastSubviewOnY{
    if(self.subviews.count > 0){
        UIView *outView = self.subviews[0];
        
        for(UIView *v in self.subviews)
            if(v.y > outView.y)
                outView = v;
        
        return outView;
    }
    
    return nil;
}

#pragma mark ---------------- other-----------------
/**
 * @brief 移除此view上的所有子视图
 */
- (void)removeAllSubviews {
    [self.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeAllSubviews];
        [obj removeFromSuperview];
        obj=nil;
    }];
}

- (void)removeAllSubviewsFromTagRange:(NSRange)range {
    for (NSInteger tag = range.location; tag < range.length; tag++) {
        UIView * view = [self viewWithTag:tag];
        if (view) [view removeFromSuperview];
    }
}

- (void)removeAllSubviewsFromTag:(NSInteger)tag {
    for (UIView *view in self.subviews) {
        if (view.tag >= tag) {
            [view removeFromSuperview];
        }
    }
}

- (BOOL)containViewWithTag:(NSUInteger)tag {
    __block BOOL contained = NO;
    [self.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj tag]==tag) {
            *stop = YES;
            contained = YES;
        }
    }];
    return contained;
}

//用来暂停layer上的动画
- (void)pauseLayer {
    CFTimeInterval pausedTime = [self.layer convertTime:CACurrentMediaTime() fromLayer:nil];
    self.layer.speed = 0.0;
    self.layer.timeOffset = pausedTime;
}
//恢复layer上的动画
- (void)resumeLayer {
    CFTimeInterval pausedTime = [self.layer timeOffset];
    self.layer.speed = 1.0;
    self.layer.timeOffset = 0.0;
    self.layer.beginTime = 0.0;
    CFTimeInterval timeSincePause = [self.layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
    self.layer.beginTime = timeSincePause;
}

- (void)shadowWothOffset:(CGSize)offset radius:(CGFloat)radius opacity:(CGFloat)opacity color:(UIColor *)color {
    
    if ([color isEqual:[UIColor clearColor]]) {
        
        self.clipsToBounds = YES;
        self.layer.masksToBounds = YES;
        
    } else {
        
        self.clipsToBounds = NO;
        self.layer.masksToBounds = NO;
    }
    self.layer.shadowOpacity = opacity;
    self.layer.shadowOffset = offset;
    self.layer.shadowRadius = radius;
    self.layer.shadowColor = color.CGColor;
    if (self.width && self.height) {
        
        self.layer.shadowPath = [UIBezierPath bezierPathWithRect:self.bounds].CGPath;
    }
}

- (BOOL)frameIsEqualTo:(CGRect)frame {
    
    NSInteger counter = 0;
    if (self.x == frame.origin.x) counter++;
    if (self.y == frame.origin.y) counter++;
    if (self.width == frame.size.width) counter++;
    if (self.height == frame.size.height) counter++;
    
    return counter==4;
}

- (UIView *)subviewWithTag:(NSInteger)tag {
    
    UIView * view = nil;
    for (UIView * each in self.subviews) {
        
        if (each.tag==tag) {
            
            view = each;
            break;
        }
    }
    return view;
}

+ (UIView*)createView:(CGRect)frame color:(UIColor *)color tag:(NSInteger)tag {
    UIView * view = [[UIView alloc]initWithFrame:frame];
    [view setTag:tag];
    [view setBackgroundColor:color];
    return view;
}

+ (void)removeSubviews:(NSArray *)subviews {
    for (UIView * tView in subviews) {
        [tView removeFromSuperview];
    }
}

+ (void)removeSubviews:(NSArray *)subviews forSubViewClass:(Class)subviewClass {
    for (UIView * tview in subviews) {
        if ([tview isKindOfClass:subviewClass]) {
            [tview removeFromSuperview];
        }
    }
}

- (void)printSubviews {
    [[self subviews] enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSLog(@"[%ld]:%@", (unsigned long)idx, obj);
    }];
}

- (void)printAllSubviews {
    __weak typeof(self) wself = self;
    [[self subviews] enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSLog(@"super[%@][%ld]:%@", [wself description], (unsigned long)idx, obj);
        [obj printAllSubviews];
    }];
}

- (UIImage *)snapshotImage {
    UIGraphicsBeginImageContextWithOptions(self.size, YES, 0.0f);
    [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

- (void)selectedButton:(UIButton *)button {
    [[self subviews] enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:[UIButton class]]) {
            UIButton * each = (UIButton*)obj;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [each setHighlighted:([button tag]==[each tag])];
                [each setEnabled:!([button tag]==[each tag])];
                [each.layer transform:kCATransitionFade subType:kCATransitionFromRight];
            });
        }
    }];
}

+ (UIWindow *)showingWindow {
    __block UIWindow * keyWindow = [[UIApplication sharedApplication] keyWindow];
    if (!keyWindow||!(keyWindow.windowLevel==UIWindowLevelNormal)) {
        [[[UIApplication sharedApplication] windows] enumerateObjectsUsingBlock:^(__kindof UIWindow * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.windowLevel==UIWindowLevelNormal) {
                *stop = YES;
                keyWindow = obj;
            }
        }];
    }
    return keyWindow;
}

- (void)subScrollViewScrollsEnable:(BOOL)enable {
    [self.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj respondsToSelector:@selector(setScrollEnabled:)]) {
            [(UIScrollView*)obj setScrollEnabled:enable];
        }
    }];
}

@end

@implementation CALayer (Category)


@dynamic x;
@dynamic y;
@dynamic width;
@dynamic height;
@dynamic origin;
@dynamic size;

#pragma mark ---------------- Setters-----------------
-(void)setX:(CGFloat)x{
    CGRect r        = self.frame;
    r.origin.x      = x;
    self.frame      = r;
}

-(void)setY:(CGFloat)y{
    CGRect r        = self.frame;
    r.origin.y      = y;
    self.frame      = r;
}

-(void)setWidth:(CGFloat)width{
    CGRect r        = self.frame;
    r.size.width    = width;
    self.frame      = r;
}

-(void)setHeight:(CGFloat)height{
    CGRect r        = self.frame;
    r.size.height   = height;
    self.frame      = r;
}

-(void)setOrigin:(CGPoint)origin{
    self.x          = origin.x;
    self.y          = origin.y;
}

-(void)setSize:(CGSize)size{
    self.width      = size.width;
    self.height     = size.height;
}

-(void)setRight:(CGFloat)right {
    CGRect frame = self.frame;
    frame.origin.x = right - frame.size.width;
    self.frame = frame;
}

-(void)setBottom:(CGFloat)bottom {
    CGRect frame = self.frame;
    frame.origin.y = bottom - frame.size.height;
    self.frame = frame;
}

#pragma mark ---------------- Getters-----------------
-(CGFloat)x{
    return self.frame.origin.x;
}

-(CGFloat)y{
    return self.frame.origin.y;
}

-(CGFloat)width{
    return self.frame.size.width;
}

-(CGFloat)height{
    return self.frame.size.height;
}

-(CGPoint)origin{
    return CGPointMake(self.x, self.y);
}

-(CGSize)size{
    return CGSizeMake(self.width, self.height);
}

-(CGFloat)right {
    return self.frame.origin.x + self.frame.size.width;
}

-(CGFloat)bottom {
    return self.frame.origin.y + self.frame.size.height;
}

#pragma mark - other
- (void)transform:(NSString*)type subType:(NSString*)subType {
    [self transform:type subType:subType interval:0.25f];
}

- (void)transform:(NSString *)type subType:(NSString *)subType interval:(NSTimeInterval)interval {
    CATransition * transition = [CATransition animation];
    transition.type = type;
    transition.subtype = subType;
    transition.repeatCount = 0;
    transition.duration = interval;
    [self addAnimation:transition forKey:[self description]];
}

- (void)transform:(NSString *)type subType:(NSString *)subType complete:(dispatch_block_t)complete {
    NSTimeInterval interval = 0.25f;
    [self transform:type subType:subType interval:interval];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(interval * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (complete) complete();
    });
}

@end
